// 表格ms-table使用
import { computed, onMounted, reactive, watch } from 'vue'
import { get } from '@/api'
import { TResponse } from '@/typings'

export interface ITablesOptions {
  api: string;
  firstLoad?: boolean;
}

export interface IUseTableData {
  page: number;
  limit: number;
  total: number;
  loading: boolean;
  dataSource: Array<any>;
}

interface ITableResult {
  records: Array<any>;
  total: number;
}

const useTables = (option: ITablesOptions) => {
  // 默认值
  const defaultOptions = {
    firstLoad: true
  }

  const state = reactive<IUseTableData>({
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    dataSource: []
  })

  const options = computed<ITablesOptions>(() => Object.assign(option, defaultOptions))

  // 根据当前状态 查询表格
  const handleGetTable = (): void => {
    state.loading = true
    get(options.value.api, { page: state.page, limit: state.limit }).then((res: TResponse<ITableResult>) => {
      const { records, total } = res.result
      state.total = total
      state.dataSource = records
    }).finally(() => {
      state.loading = false
    })
  }

  watch([() => state.page, () => state.limit], handleGetTable)

  onMounted(() => { options.value.firstLoad && handleGetTable() })

  return {
    handleGetTable,
    state
  }
}

export default useTables
